<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Hello world</title>
	<style>
		* {
			margin: 0;
			padding: 0;
		}
		.box {
			position: fixed;
			top: 50%;
			left: 50%;
			margin-top: -40vh;
			margin-left: -40vw;
			width: 80vw;
			height: 80vh;
			border: 1px solid #ccc;
		}
		.edit-line-box {
        position: absolute;
        z-index: -10;
        opacity: 0;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .edit-line-box.is-show {
        z-index: 10;
        opacity: 1;
    }
    .edit-line-box .close-btn {
        position: absolute;
        z-index: 50;
        top: 10px;
        right: 10px;
        text-align: center;
        width: 30px;
        line-height: 30px;
        border: 1px solid #333;
        border-radius: 50%;
        font-size: 26px;
        cursor: pointer;
    }
    .edit-line-box .edit-box-container {
        position: relative;
        width: 100%;
        height: 100%;
    }
    .edit-line-drag-box {
        position: absolute;
        z-index: 10;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }
    .edit-line-drag-box .green {
        position: absolute;
        z-index: 5;
        background: green;
    }
    .edit-line-drag-box .black {
        position: absolute;
        z-index: 6;
        background: black;
    }
    .edit-line-drag-box .red-left, .edit-line-drag-box .red-right {
        position: absolute;
        z-index: 7;
        background: red;
    }
    .edit-line-drag-box .before, .edit-line-drag-box .after {
        position: absolute;
        top: 50%;
        margin-top: -3px;
        z-index: 10;
        width: 6px;
        height: 6px;
        cursor: e-resize;
    }
    .edit-line-drag-box .before {
        left: 0;
    }
    .edit-line-drag-box .after {
        right: 0;
    }
    .edit-line-drag-box .line {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        cursor: n-resize;
    }
    .edit-line-drag-box .xxb {
        position: absolute;
        z-index: 1;
        bottom: 10px;
        left: 0;
        right: 0;
        text-align: center;
        font-size: 30px;
        color: #409EFF;
    }
    .edit-line-box .edit-box-container .imageContainer {
    	display: flex;
    	align-items: center;
    	justify-content: center;
    }

    .aa {
    	width: 100%;
    	height: 100%;
    }
	</style>
</head>
<body>
	<button onclick="showEditClick()">显示</button>
	<button onclick="okEditLine()">隐藏</button>
	<div class="box">
		<div class="aa"></div>
		<div class="edit-line-box">
	      <div class="edit-box-container">
	          <div class="close-btn" onclick="oLine.close()">×</div>
	          <div style="width:100%; height:100%;" class="imageContainer"></div>
	          <div class="edit-line-drag-box">
	              <div class="green">
	                  <div class="line" data-dis="y" data-key="lung_y" title="上下拖动"></div>
	                  <div class="before" data-dis="x" data-key="lung_x_begin" title="左右拖动"></div>
	                  <div class="after" data-dis="x" data-key="lung_x_end" title="左右拖动"></div>
	              </div>
	              <div class="black"></div>
	              <div class="red-left">
	                  <div class="line" data-dis="y" data-key="heart_y_begin_left" title="上下拖动"></div>
	                  <div class="before" data-dis="x" data-key="heart_x_begin_left" title="左右拖动"></div>
	              </div>
	              <div class="red-right">
	                  <div class="line" data-dis="y" data-key="heart_y_end_right" title="上下拖动"></div>
	                  <div class="after" data-dis="x" data-key="heart_x_end_right" title="左右拖动"></div>
	              </div>
	              <div class="xxb"></div>
	          </div>
	      </div>
	  </div>
	</div>


<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="./static/hammer.js"></script>
<script src="./static/cornerstone.min.js"></script>
<script src="./static/cornerstoneMath.min.js"></script>
<script src="./static/cornerstoneWADOImageLoader.min.js"></script>
<script src="./static/cornerstoneWebImageLoader.min.js"></script>
<script src="./static/cornerstoneTools.min.js"></script>
<script src="./static/dicomParser.min.js"></script>
<script>

	const baseUrl = "http://127.0.0.1:8000/static/js/";

	window.onload = function () {
      _initCornerstone();

      aaInitCornerstone();

      oLine.init();

     //  setTimeout(() => {
     //  	oLine.show({
     //  		center_x: 1277,
					// heart_x_begin_left: 936,
					// heart_x_end_right: 2100,
					// heart_y_begin_left: 1531,
					// heart_y_end_right: 1621,
					// lung_x_begin: 170,
					// lung_x_end: 2348,
					// lung_y: 1565,
					// ratio: 0.5344,
     //  	})
     //  }, 1500);
  }

  function _initCornerstone() {
      cornerstoneWADOImageLoader.external.cornerstone = cornerstone;
      cornerstoneWADOImageLoader.external.dicomParser = dicomParser;
      cornerstoneTools.external.cornerstoneMath = cornerstoneMath;
      cornerstoneTools.external.cornerstone = cornerstone;
      cornerstoneTools.external.Hammer = Hammer;

      // Image Loader
      const config = {
          webWorkerPath: `${baseUrl}assets/image-loader/cornerstoneWADOImageLoaderWebWorker.js`,
          taskConfiguration: {
              decodeTask: {
                  codecsPath: `${baseUrl}assets/image-loader/cornerstoneWADOImageLoaderCodecs.js`,
              },
          },
      };
      cornerstoneWADOImageLoader.webWorkerManager.initialize(config);
  }

  // 初始化影像
  function aaInitCornerstone() {
  		let element = document.querySelector('.aa');
      cornerstone.enable(element);
      cornerstone.loadAndCacheImage('wadouri:http://localhost:8088/static/data/1.2.840.1.19439.0.1000.20220101135814.1480.10000.3383824/1.2.840.113564.12312312366.2022010113510529628.1003000225002').then(function (image) {
          var viewport = cornerstone.getDefaultViewportForImage(element, image);
          cornerstone.displayImage(element, image, viewport);
      });
      element.addEventListener('cornerstoneimagerendered', onImageRendered);

      // setTimeout(() => {
      // 	drawCTR();
      // }, 500);
  }

  function onImageRendered(e) {
  	console.log(e);
  	let context = e.detail.canvasContext;
  	drawCTR({
	 		center_x: 1277,
			heart_x_begin_left: 936,
			heart_x_end_right: 2100,
			heart_y_begin_left: 1531,
			heart_y_end_right: 1621,
			lung_x_begin: 170,
			lung_x_end: 2348,
			lung_y: 1565,
			ratio: 0.5344,
  	}, context)
  }


  function drawCTR(ctr, context) {
	    console.log(ctr, context);
	    contentes = ""
	    context.beginPath();
	    context.lineWidth = 15;
	    context.strokeStyle = "green"
	    context.moveTo(ctr["lung_x_begin"], ctr["lung_y"]);
	    context.lineTo(ctr["lung_x_end"], ctr["lung_y"]);
	    context.closePath();
	    context.stroke();
	    centerX = (ctr["lung_x_begin"] + ctr["lung_x_end"]) / 2
	    Y = [ctr["lung_y"], ctr["heart_y_begin_left"], ctr["heart_y_end_right"]]
	    minY = Math.min(...Y)
	    maxY = Math.max(...Y)
	    context.strokeStyle = "black"
	    context.beginPath();
	    context.moveTo(centerX, minY - 50);
	    context.lineTo(centerX, maxY + 50);
	    context.closePath();
	    context.stroke();
	    context.strokeStyle = "red"
	    context.beginPath();
	    context.moveTo(ctr["heart_x_begin_left"], ctr["heart_y_begin_left"]);
	    context.lineTo(centerX, ctr["heart_y_begin_left"]);
	    context.closePath();
	    context.stroke();
	    context.beginPath();
	    context.moveTo(centerX, ctr["heart_y_end_right"]);
	    context.lineTo(ctr["heart_x_end_right"], ctr["heart_y_end_right"]);
	    context.closePath();
	    context.stroke();
	}

	// 显示编辑线
  function showEditClick() {
     oLine.show({
    		center_x: 1277,
				heart_x_begin_left: 936,
				heart_x_end_right: 2100,
				heart_y_begin_left: 1531,
				heart_y_end_right: 1621,
				lung_x_begin: 170,
				lung_x_end: 2348,
				lung_y: 1565,
				ratio: 0.5344,
    	})
  }
  // 确定
  function okEditLine() {
      oLine.close();
  }

	
	// 划线对象
  var oLine = {
    visible: false,
    img: {
        w: 0,
        h: 0
    },
    ratio: '',
    dragsize: '',

    oldctr: null,
    newctr: null,

    // canvas对象
    context: null,

    // 是否编辑过
    editGreen: false,
    editRedLeft: false,
    editRefRight: false,
    // 节点
    oEditBox: document.querySelector('.edit-line-box'),
    oContainer: null,
    oGreen: null,
    oBlack: null,
    oRedLeft: null,
    oRedRight: null,
    oXxb: null,
    // 是否已初始化事件
    isInited: false,
    // 移动
    move: {
        isdown: false,
        startCtr: null,
        key: '',
        dis: '',
        downx: 0,
        downy: 0,
    },
    show(ctr) {
        this.oldctr = JSON.parse(JSON.stringify(ctr));
        this.newctr = JSON.parse(JSON.stringify(ctr));
        this.drawLine();

        // $('#editBtn').text('保存');
        $(this.oEditBox).addClass('is-show');
        // $('#myNavbar > .nav').hide();
        this.visible = true;

        // this.drawCTR();
    },
    save() {
        infos[image_uir + "ctr"] = this.newctr;
        drawReload($('#ctr_select').is(':checked'));
        setXxb(this.newctr.ratio);
        this.close();
    },
    close() {
        // $('#editBtn').text('编辑');
        $(this.oEditBox).removeClass('is-show');
        // $('#myNavbar > .nav').show();
        this.visible = false;
    },
    init() {
        if(this.isInited) {
            return;
        }
        this.isInited = true;
        // 节点
        this.oContainer = this.oEditBox.querySelector('.edit-box-container');
        this.oGreen = this.oEditBox.querySelector('.green');
        this.oBlack = this.oEditBox.querySelector('.black');
        this.oRedLeft = this.oEditBox.querySelector('.red-left');
        this.oRedRight = this.oEditBox.querySelector('.red-right');
        this.oXxb = this.oEditBox.querySelector('.xxb');
        this.oElement = this.oEditBox.querySelector('.imageContainer');

        // 初始化影像
        this.initCornerstone();
        // 初始化事件
        this.initEvent();
    },
    // 初始化影像
    initCornerstone() {
        var _this = this;
        cornerstone.enable(this.oElement);
        cornerstone.loadAndCacheImage('wadouri:http://localhost:8088/static/data/1.2.840.1.19439.0.1000.20220101135814.1480.10000.3383824/1.2.840.113564.12312312366.2022010113510529628.1003000225002').then(function (image) {
            _this.img.w = image.width;
            _this.img.h = image.height;
            _this.setParam();

            var viewport = cornerstone.getDefaultViewportForImage(_this.oElement, image);
            cornerstone.displayImage(_this.oElement, image, viewport);
        });
    },

    // 初始化window移动
    initEvent() {
        var _this = this;
        var dom =  $(this.oEditBox).find('.line, .before, .after');
        $(this.oEditBox).find('.line, .before, .after').on('mousedown', function (e) {
            _this.move.isdown = true;
            _this.move.startCtr = JSON.parse(JSON.stringify(_this.newctr));
            _this.move.dis = e.target.dataset.dis;
            _this.move.key = e.target.dataset.key;
            _this.move.downx = e.pageX;
            _this.move.downy = e.pageY;
        })
        window.addEventListener('mousemove', function (e) {
            if(!_this.move.isdown) {
                return;
            }
            var movex = e.pageX - _this.move.downx;
            var movey = e.pageY - _this.move.downy;
            _this.saveDrag(movex, movey);
        })
        window.addEventListener('mouseup', function (e) {
            if(!_this.move.isdown) {
                return;
            }
            _this.move.isdown = false;
        })
    },

    // 设置参数
    setParam() {
    	// 设置图片宽高
      var boxw = this.oEditBox.clientWidth, boxh = this.oEditBox.clientHeight;
      var min = Math.min(boxw, boxh);
      if(boxw/boxh >= this.img.w/this.img.h) {
          this.oContainer.style.width = boxh*(this.img.w/this.img.h)+'px';
          this.oContainer.style.height = boxh+'px';
          // 计算比例
          this.ratio = this.img.h/boxh;
      }  else {
          this.oContainer.style.width = boxw+'px';
          this.oContainer.style.height = boxw/(this.img.w/this.img.h)+'px';
          // 计算比例
          this.ratio = this.img.w/boxw;
      }
      // 设置线的尺寸
      this.dragsize = 15/this.ratio;
    },

    // 保存移动结果
    saveDrag(movex, movey) {
        // 改变值
        this.newctr[this.move.key] = (this.move.dis == 'x' ? movex : movey)*this.ratio+this.move.startCtr[this.move.key];
        // 计算心胸比
        this.newctr.ratio = (this.newctr.heart_x_end_right-this.newctr.heart_x_begin_left)/(this.newctr.lung_x_end-this.newctr.lung_x_begin);
        // 画内容
        this.drawLine();
    },

    // 绘制DOM
    drawLine() {
        var ctr = this.newctr;
        // 绿色线
        this.oGreen.style.height = this.dragsize+'px';
        this.oGreen.style.left = ctr.lung_x_begin/this.ratio+'px';
        this.oGreen.style.right = (this.img.w-ctr.lung_x_end)/this.ratio+'px';
        this.oGreen.style.top = ctr.lung_y/this.ratio-this.dragsize/2+'px';

        var centerX = (ctr.lung_x_begin + ctr.lung_x_end) / 2
        var Y = [ctr.lung_y, ctr.heart_y_begin_left, ctr.heart_y_end_right]
        var minY = Math.min(...Y)
        var maxY = Math.max(...Y)

        // 黑色线
        this.oBlack.style.width = this.dragsize+'px';
        this.oBlack.style.left = centerX/this.ratio-this.dragsize/2+'px';
        this.oBlack.style.top = (minY - 50)/this.ratio+'px';
        this.oBlack.style.bottom = (this.img.h-(maxY + 50))/this.ratio+'px';

        // 红色左
        this.oRedLeft.style.height = this.dragsize+'px';
        this.oRedLeft.style.left = ctr.heart_x_begin_left/this.ratio+'px';
        this.oRedLeft.style.right = (this.img.w-centerX)/this.ratio+'px';
        this.oRedLeft.style.top = ctr.heart_y_begin_left/this.ratio-this.dragsize/2+'px';

        // 红色右
        this.oRedRight.style.height = this.dragsize+'px';
        this.oRedRight.style.left = centerX/this.ratio+'px';
        this.oRedRight.style.right = (this.img.w-ctr.heart_x_end_right)/this.ratio+'px';
        this.oRedRight.style.top = ctr.heart_y_end_right/this.ratio-this.dragsize/2+'px';

        // 设置心胸比
        this.oXxb.innerHTML = '心胸比：'+ctr.ratio.toFixed(2);

        // this.updateTheImage();
        // this.drawCTR();
    },

    drawCTR() {
      console.log(this.newctr, this.context);
	    let ctr = this.newctr;
	    let context = this.context;
	    context.beginPath();
	    context.lineWidth = 15;
	    context.strokeStyle = "green"
	    context.moveTo(ctr["lung_x_begin"], ctr["lung_y"]);
	    context.lineTo(ctr["lung_x_end"], ctr["lung_y"]);
	    context.closePath();
	    context.stroke();
	    centerX = (ctr["lung_x_begin"] + ctr["lung_x_end"]) / 2
	    Y = [ctr["lung_y"], ctr["heart_y_begin_left"], ctr["heart_y_end_right"]]
	    minY = Math.min(...Y)
	    maxY = Math.max(...Y)
	    context.strokeStyle = "black"
	    context.beginPath();
	    context.moveTo(centerX, minY - 50);
	    context.lineTo(centerX, maxY + 50);
	    context.closePath();
	    context.stroke();
	    context.strokeStyle = "red"
	    context.beginPath();
	    context.moveTo(ctr["heart_x_begin_left"], ctr["heart_y_begin_left"]);
	    context.lineTo(centerX, ctr["heart_y_begin_left"]);
	    context.closePath();
	    context.stroke();
	    context.beginPath();
	    context.moveTo(centerX, ctr["heart_y_end_right"]);
	    context.lineTo(ctr["heart_x_end_right"], ctr["heart_y_end_right"]);
	    context.closePath();
	    context.stroke();
		},

		updateTheImage() {
			var _this = this;
        cornerstone.loadAndCacheImage('wadouri:http://localhost:8088/static/data/1.2.840.1.19439.0.1000.20220101135814.1480.10000.3383824/1.2.840.113564.12312312366.2022010113510529628.1003000225002').then(function (image) {
            var viewport = cornerstone.getDefaultViewportForImage(_this.oElement, image);
            cornerstone.displayImage(_this.oElement, image, viewport);
        });
        _this.oElement.addEventListener('cornerstoneimagerendered', function (e) {

        });
    },

    // 鼠标按下
    mousedown(e) {
        console.log(e);
    }
  }

</script>
</body>
</html>